﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Experimentor
{
    public static class ExcelSave
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void createSequenceSheet(ExcelWorkbook workbook, string sheetName)
        {
            ExcelWorksheet sheet = workbook.Worksheets.Add(sheetName);
            sheet.Row(1).Style.Font.Bold = true;
            sheet.Cells[1, 1].Value = "ID";
            sheet.Cells[1, 2].Value = "SetOrder";
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void addToSequenceSheet(ExcelWorkbook workbook, string sheetName, string cellName)
        {
            ExcelWorksheet sheet = workbook.Worksheets[sheetName];
            int column = 3;
            while (sheet.Cells[1, column].Value != null && sheet.Cells[1, column].Value.ToString() != cellName) column++;
            sheet.Cells[1, column].Value = cellName;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void addToSetorder(ExcelWorkbook workbook, string sheetName, string ID, int set)
        {
            ExcelWorksheet sheet = workbook.Worksheets[sheetName];
            int row = 2;
            while (sheet.Cells[row, 1].Value != null && sheet.Cells[row, 1].Value.ToString() != ID) row++;
            if (sheet.Cells[row, 2].Value == null) sheet.Cells[row, 2].Value = set;
            else sheet.Cells[row, 2].Value = sheet.Cells[row, 2].Value.ToString() + ";" + set;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void storeValue(ExcelWorkbook workbook, string sheetName, string ID, string cellName, object tostore)
        {
            ExcelWorksheet sheet = workbook.Worksheets[sheetName];
            int row = 2;
            while (sheet.Cells[row, 1].Value != null && sheet.Cells[row, 1].Value.ToString() != ID) row++;
            if (sheet.Cells[row, 1].Value == null || sheet.Cells[row, 1].Value.ToString() != ID) sheet.Cells[row, 1].Value = ID;
            int column = 2;
            while (sheet.Cells[1, column].Value != null && sheet.Cells[1, column].Value.ToString() != cellName) column++;
            sheet.Cells[1, column].Value = cellName;
            if (tostore.GetType() != typeof(Uri)) sheet.Cells[row, column].Value = tostore;
            else
            {
                Uri uri = tostore as Uri;
                sheet.Cells[row, column].Formula = "HYPERLINK(\"" + uri.LocalPath + "\",\"" + System.IO.Path.GetFileName(uri.LocalPath) + "\")";
            }
        }

    }
}
